/// 🎯 个人信息编辑表单模型
/// 
/// 职责：
/// - 统一管理所有表单字段
/// - 封装表单验证逻辑
/// - 智能变更检测
/// - 转换为请求模型
/// 
/// 对应页面：peofile_detial
class ProfileEditForm {
  // ==================== 表单字段 ====================
  
  /// 昵称
  String nickname = '';
  
  /// 邮箱（可选）
  String email = '';
  
  /// 手机号（可选）
  String phone = '';
  
  /// 性别
  String gender = '';
  
  /// 生日
  String birthday = '';
  
  /// 城市
  String city = '';
  
  /// 个性签名
  String signature = '';
  
  /// 常出没地
  String frequentPlaces = '';
  
  /// 爱好列表
  List<String> hobbies = [];
  
  /// 相册图片URL列表
  List<String> albumImages = [];
  
  // ==================== 原始值（用于变更检测）====================
  
  String _originalNickname = '';
  String _originalEmail = '';
  String _originalPhone = '';
  String _originalGender = '';
  String _originalBirthday = '';
  String _originalCity = '';
  String _originalSignature = '';
  String _originalFrequentPlaces = '';
  List<String> _originalHobbies = [];
  List<String> _originalAlbumImages = [];
  
  // ==================== 构造函数 ====================
  
  ProfileEditForm();
  
  /// 从用户实体初始化表单
  factory ProfileEditForm.fromUserEntity(dynamic userEntity) {
    final form = ProfileEditForm();
    
    // 初始化当前值
    form.nickname = userEntity.username ?? '';
    form.email = userEntity.userEmail ?? '';
    form.phone = userEntity.userPhone ?? '';
    form.gender = userEntity.userGender ?? '';
    form.birthday = userEntity.userBirthday ?? '';
    form.city = userEntity.userCity ?? '';
    form.signature = userEntity.userSignature ?? '';
    form.frequentPlaces = userEntity.userFrequentPlaces ?? '';
    
    // 解析爱好
    if (userEntity.userHobbies is String && userEntity.userHobbies.isNotEmpty) {
      form.hobbies = userEntity.userHobbies.split(',');
    } else if (userEntity.userHobbies is List) {
      form.hobbies = List<String>.from(userEntity.userHobbies);
    }
    
    // 解析相册图片
    if (userEntity.userImgUrls is String && userEntity.userImgUrls.isNotEmpty) {
      form.albumImages = userEntity.userImgUrls.split(',');
    } else if (userEntity.userImgUrls is List) {
      form.albumImages = List<String>.from(userEntity.userImgUrls);
    }
    
    // 保存原始值
    form._saveOriginalValues();
    
    return form;
  }
  
  /// 保存原始值（用于变更检测）
  void _saveOriginalValues() {
    _originalNickname = nickname;
    _originalEmail = email;
    _originalPhone = phone;
    _originalGender = gender;
    _originalBirthday = birthday;
    _originalCity = city;
    _originalSignature = signature;
    _originalFrequentPlaces = frequentPlaces;
    _originalHobbies = List<String>.from(hobbies);
    _originalAlbumImages = List<String>.from(albumImages);
  }
  
  // ==================== 表单验证 ====================
  
  /// 验证昵称
  String? validateNickname() {
    if (nickname.trim().isEmpty) {
      return '昵称不能为空';
    }
    if (nickname.trim().length < 2) {
      return '昵称至少2个字符';
    }
    if (nickname.trim().length > 20) {
      return '昵称不能超过20个字符';
    }
    return null;
  }
  
  /// 验证邮箱
  String? validateEmail() {
    if (email.trim().isEmpty) {
      return null; // 邮箱可以为空
    }
    
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    if (!emailRegex.hasMatch(email.trim())) {
      return '请输入有效的邮箱地址';
    }
    return null;
  }
  
  /// 验证手机号
  String? validatePhone() {
    if (phone.trim().isEmpty) {
      return null; // 手机号可以为空
    }
    
    final phoneRegex = RegExp(r'^1[3-9]\d{9}$');
    if (!phoneRegex.hasMatch(phone.trim())) {
      return '请输入有效的手机号码';
    }
    return null;
  }
  
  /// 整体表单验证
  bool get isValid {
    return validateNickname() == null &&
           validateEmail() == null &&
           validatePhone() == null;
  }
  
  /// 获取所有验证错误
  Map<String, String> get validationErrors {
    final errors = <String, String>{};
    
    final nicknameError = validateNickname();
    if (nicknameError != null) errors['nickname'] = nicknameError;
    
    final emailError = validateEmail();
    if (emailError != null) errors['email'] = emailError;
    
    final phoneError = validatePhone();
    if (phoneError != null) errors['phone'] = phoneError;
    
    return errors;
  }
  
  // ==================== 变更检测 ====================
  
  /// 🎯 智能变更检测 - 返回真正改变的字段
  Map<String, dynamic> detectChanges() {
    final changes = <String, dynamic>{};
    
    // 检测昵称变更
    if (nickname.trim() != _originalNickname) {
      changes['username'] = nickname.trim();
    }
    
    // 检测邮箱变更
    if (email.trim() != _originalEmail) {
      changes['userEmail'] = email.trim();
    }
    
    // 检测手机号变更
    if (phone.trim() != _originalPhone) {
      changes['userPhone'] = phone.trim();
    }
    
    // 检测性别变更
    if (gender != _originalGender) {
      changes['userGender'] = gender;
    }
    
    // 检测生日变更
    if (birthday != _originalBirthday) {
      changes['userBirthday'] = birthday;
    }
    
    // 检测城市变更
    if (city != _originalCity) {
      changes['userCity'] = city;
    }
    
    // 检测签名变更
    if (signature != _originalSignature) {
      changes['userSignature'] = signature;
    }
    
    // 检测常出没地变更
    if (frequentPlaces != _originalFrequentPlaces) {
      changes['userFrequentPlaces'] = frequentPlaces;
    }
    
    // 检测爱好变更
    if (!_listEquals(hobbies, _originalHobbies)) {
      changes['userHobbies'] = hobbies;
    }
    
    // 检测相册图片变更
    if (!_listEquals(albumImages, _originalAlbumImages)) {
      changes['userImgUrls'] = albumImages;
    }
    
    return changes;
  }
  
  /// 是否有任何变更
  bool get hasChanges {
    return detectChanges().isNotEmpty;
  }
  
  /// 比较两个列表是否相等
  bool _listEquals(List<dynamic> list1, List<dynamic> list2) {
    if (list1.length != list2.length) return false;
    for (int i = 0; i < list1.length; i++) {
      if (list1[i] != list2[i]) return false;
    }
    return true;
  }
  
  // ==================== 转换方法 ====================
  
  /// 🎯 转换为更新用户信息的请求参数
  /// 
  /// 注意：这里不是转换为独立的Request模型，
  /// 而是直接转换为API需要的Map格式（符合当前架构）
  Map<String, dynamic> toUpdateRequest() {
    return detectChanges(); // 只返回变更的字段
  }
  
  /// 重置表单到原始状态
  void reset() {
    nickname = _originalNickname;
    email = _originalEmail;
    phone = _originalPhone;
    gender = _originalGender;
    birthday = _originalBirthday;
    city = _originalCity;
    signature = _originalSignature;
    frequentPlaces = _originalFrequentPlaces;
    hobbies = List<String>.from(_originalHobbies);
    albumImages = List<String>.from(_originalAlbumImages);
  }
  
  // ==================== 调试方法 ====================
  
  @override
  String toString() {
    return '''
ProfileEditForm {
  nickname: $nickname,
  email: $email,
  phone: $phone,
  gender: $gender,
  birthday: $birthday,
  city: $city,
  signature: $signature,
  frequentPlaces: $frequentPlaces,
  hobbies: $hobbies,
  albumImages: ${albumImages.length} 张,
  hasChanges: $hasChanges
}''';
  }
}

